package com.dream.mygateway;

import jakarta.validation.constraints.NotEmpty;
import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;

/**
 * @author Dreamer
 */
@Component
public class MyRoutePredicateFactory extends AbstractRoutePredicateFactory<MyRoutePredicateFactory.Config>
{



    public MyRoutePredicateFactory() {
        super(MyRoutePredicateFactory.Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList("userType");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {

                String userType = serverWebExchange.getRequest().getQueryParams().getFirst("userType");

                Optional<String> ut = Optional.ofNullable(userType);

                return ut.filter(s -> config != null && s.equals(config.getUserType()))
                        .isPresent();
            }
        };
    }

    public static class Config {

        @Setter
        @Getter
        @NotEmpty
        private String userType;   //钻金银用户等级   根据yml文件中配置哪些路由 给对应的等级访问

    }

    
}